<template>
  <el-drawer
    :title="drawerTitle[drawerType]"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="beforeClose"
    custom-class="tag-drawer audit-process-drawer"
    v-drawerResize
  >
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
          <el-form-item label="审批流程名称" prop="auditName">
            <el-col :span="24">
              <el-input placeholder="请输入审批流程名称" v-model="editForm.auditName"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="审批流程备注" prop="remarks">
            <el-col :span="24">
              <el-input
                placeholder="请输入审批流程备注"
                v-model="editForm.remarks"
                type="textarea"
                :rows="3"
                resize="none"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="状态" prop="auditStatus">
            <el-col :span="24">
              <el-switch active-color="#13ce66" v-model="editForm.auditStatus" :active-value="1" :inactive-value="0">
              </el-switch>
            </el-col>
          </el-form-item>

          <el-form-item label="申请方" prop="applicantId">
            <el-col :span="12">
              <tag-rules :ruleId="editForm.applicantId" :ruleName="editForm.applicant" @confirm="ruleSave"></tag-rules>
            </el-col>
          </el-form-item>
          <el-form-item label="审批方" prop="priority">
            <el-row class="user-form">
              <div class="new-button">
                <el-button type="primary" @click="addPriorityForm()">新增优先级</el-button>
                <el-button type="primary" @click="removePriorityForm()">删除优先级</el-button>
              </div>
              <el-row
                class="user-form priority-form"
                v-for="(formItem, formIndex) in editForm.priority"
                :key="formIndex"
              >
                <el-row :gutter="20" v-if="formItem.procAppr.length !== 0" class="user-title">
                  <el-col :span="3">(第{{ formIndex + 1 }}级)</el-col>
                  <el-col :span="6">公司</el-col>
                  <el-col :span="6">部门</el-col>
                  <el-col :span="6">用户</el-col>
                  <el-button
                    class="button-col-top"
                    type="primary"
                    icon="el-icon-delete"
                    plain
                    circle
                    @click="removePriorityForm(formIndex)"
                  ></el-button>
                </el-row>
                <el-row :gutter="20" v-for="(item, index) in formItem.procAppr" :key="index">
                  <el-col :span="6" :offset="3">
                    <el-form-item
                      label-width="0"
                      :prop="`priority[${formIndex}].procAppr[${index}].compId`"
                      :rules="{
                        required: true,
                        message: '公司不能为空',
                        trigger: 'change'
                      }"
                    >
                      <el-select v-model="item.compId" placeholder="请选择公司" @change="compChange(item)">
                        <template v-for="comp in compList">
                          <el-option :key="comp.compId" :label="comp.compNm" :value="comp.compId"></el-option>
                        </template>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item
                      label-width="0"
                      :prop="`priority[${formIndex}].procAppr[${index}].deptId`"
                      :rules="{
                        required: true,
                        message: '部门不能为空',
                        trigger: 'change'
                      }"
                    >
                      <el-select v-model="item.deptId" placeholder="请选择部门" @change="deptChange(item)">
                        <template v-for="dept in deptList">
                          <el-option
                            v-if="item.compId && item.compId === dept.compId"
                            :key="dept.deptId"
                            :label="dept.deptNm"
                            :value="dept.deptId"
                          ></el-option>
                        </template>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item
                      label-width="0"
                      :prop="`priority[${formIndex}].procAppr[${index}].userId`"
                      :rules="[
                        {
                          required: true,
                          message: '用户不能为空',
                          trigger: 'change'
                        },
                        { validator: checkUser, trigger: 'change' }
                      ]"
                    >
                      <el-select v-model="item.userId" placeholder="请选择用户">
                        <template v-for="user in allUserList">
                          <el-option
                            v-if="item.deptId && item.deptId === user.deptId"
                            :key="user.userId"
                            :label="user.loginUname"
                            :value="user.userId"
                          ></el-option>
                        </template>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="3" class="button-col-left">
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      plain
                      circle
                      @click="addPriorityFormRule('procAppr', formIndex, index + 1)"
                    ></el-button>
                    <el-button
                      type="primary"
                      icon="el-icon-minus"
                      plain
                      circle
                      @click="removePriorityFormRule('procAppr', formIndex, index)"
                    ></el-button>
                  </el-col>
                </el-row>
                <el-radio-group v-if="formItem.procAppr.length > 1" v-model="editForm.priority[formIndex].nexus">
                  <el-radio :label="1">与</el-radio>
                  <el-radio :label="2">或</el-radio>
                </el-radio-group>
              </el-row>
            </el-row>
          </el-form-item>

          <el-form-item label="适用范围" prop="selectModule">
            <el-transfer
              v-model="editForm.selectModule"
              filterable
              :titles="['全部模块', '已选模块']"
              :button-texts="['移除', '添加']"
              :data="moduleList"
              :props="{
                key: 'applicationModuleId',
                label: 'applicationModule'
              }"
            ></el-transfer>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="beforeClose()">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-drawer>
</template>

<script>
export default {
  data() {
    return {
      drawerVisible: false,
      drawerType: 'add',
      drawerTitle: {
        add: '新增流程',
        edit: '编辑流程'
      },
      compList: [],
      deptList: [],
      allUserList: [],
      moduleList: [],
      editForm: {
        auditId: '',
        auditName: '',
        remarks: '',
        auditStatus: 1,
        applicantId: '',
        applicant: '',
        priority: [],
        selectModule: []
      },
      editFormRules: {
        auditName: [{ required: true, message: '审批流程名称不能为空', trigger: 'blur' }],
        auditStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
        applicantId: [{ required: true, message: '请设置申请方人员规则', trigger: 'change' }],
        priority: [{ required: true, message: '审批方必须选择', trigger: 'change' }],
        selectModule: [{ required: true, message: '适用范围必须选择', trigger: 'change' }]
      }
    }
  },
  methods: {
    showDrawer(params) {
      this.drawerType = params.type
      this.getcompList()
      this.getDeptList()
      this.getUserList()
      this.getModuleList()
      if (this.drawerType === 'edit') {
        this.editForm.auditId = params.scope.auditId
        this.getAuditDetail()
      }
      this.drawerVisible = true
    },
    getcompList() {
      this.$ajax({
        url: this.$ajax.setUrl('auth/authCompMgr/list'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.compList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getDeptList() {
      this.$ajax({
        url: this.$ajax.setUrl('auth/authDeptMgr/all'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.deptList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getUserList() {
      this.$ajax({
        url: this.$ajax.setUrl('auth/authUserMgr/users'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.allUserList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getModuleList() {
      this.$ajax({
        url: this.$ajax.setUrl('module/moduleManage/selectModuleAll'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          data.data.forEach(item =>
            this.moduleList.push({ applicationModuleId: item.moduleId, applicationModule: item.moduleName })
          )
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getAuditDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`audit/auditManage/${this.editForm.auditId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          // 成功后执行的操作，返回数据在data.data中
          this.editForm.auditName = data.data.auditName
          this.editForm.remarks = data.data.remarks
          this.editForm.auditStatus = data.data.auditStatus
          this.editForm.applicantId = data.data.applicantId
          this.editForm.applicant = data.data.applicant
          this.editForm.priority = this.getProcAppr(data.data.approved)
          this.editForm.selectModule = data.data.applicationModuleId
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getProcAppr(list) {
      let arr = []
      let obj = {}
      for (let i = 0; i < list.length; i++) {
        if (!obj[list[i].apprLevel]) {
          obj[list[i].apprLevel] = {
            procAppr: [],
            nexus: list[i].levelRuleRela
          }
        }
        obj[list[i].apprLevel].procAppr.push(list[i])
      }
      for (let index in obj) {
        arr.push(obj[index])
      }
      return arr
    },
    ruleSave(data) {
      this.editForm.applicantId = data.id
      this.editForm.applicant = data.name
    },
    addPriorityFormRule(name, formIndex, index) {
      let params = {}
      params = { compId: '', deptId: '', userId: '' }
      this.editForm.priority[formIndex][name].splice(index, 0, params)
    },
    removePriorityFormRule(name, formIndex, index) {
      this.editForm.priority[formIndex][name].splice(index, 1)
      if (this.editForm.priority[formIndex][name].length === 0) {
        this.editForm.priority.splice(formIndex, 1)
      }
    },
    addPriorityForm() {
      let params = {}
      params = {
        procAppr: [{ compId: '', deptId: '', userId: '' }],
        nexus: ''
      }
      this.editForm.priority.push(params)
    },
    removePriorityForm(formIndex) {
      if (!formIndex) {
        this.editForm.priority.pop()
      } else {
        this.editForm.priority.splice(formIndex, 1)
      }
    },
    compChange(item) {
      item.deptId = ''
      item.userId = ''
    },
    deptChange(item) {
      item.userId = ''
    },
    checkPriorityAppc() {
      for (let i = 0; i < this.editForm.priority.length; i++) {
        if (this.editForm.priority[i].procAppr.length === 0) {
          return true
        }
      }
    },
    checkUser(rule, value, callback) {
      const formIndex = rule.fullField.charAt(9)
      let userIds = new Set()
      for (let i = 0; i < this.editForm.priority[formIndex].procAppr.length; i++) {
        userIds.add(this.editForm.priority[formIndex].procAppr[i].userId)
      }
      if (userIds.size !== this.editForm.priority[formIndex].procAppr.length) {
        callback(new Error('不能选择同一用户'))
      } else {
        callback()
      }
    },
    beforeClose() {
      var close = true
      var msg = ''
      if (close) {
        this.clearDrawer()
      } else {
        this.$confirm(msg)
          .then(() => {
            this.clearDrawer()
          })
          .catch(() => {})
      }
    },
    submit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let approved = []
          for (let i = 0; i < this.editForm.priority.length; i++) {
            this.editForm.priority[i].procAppr.forEach(v => {
              approved.push({
                apprProcId: this.apprProcId,
                apprLevel: i + 1,
                compId: v.compId,
                deptId: v.deptId,
                userId: v.userId,
                levelRuleRela: this.editForm.priority[i].nexus
              })
            })
          }
          let params = {
            auditName: this.editForm.auditName,
            auditStatus: this.editForm.auditStatus,
            remarks: this.editForm.remarks,
            applicantId: this.editForm.applicantId,
            applicant: this.editForm.applicant,
            applicationModuleId: this.editForm.selectModule,
            approved: JSON.stringify(approved)
          }
          if (this.drawerType === 'edit') params.auditId = this.editForm.auditId
          this.$ajax({
            url: this.$ajax.setUrl('audit/auditManage'),
            method: this.drawerType === 'edit' ? 'put' : 'post',
            data: this.$ajax.setData(params)
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.$message.success(data.msg)
              this.clearDrawer()
              this.$emit('callback')
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    },
    clearDrawer() {
      this.editForm.auditId = ''
      this.editForm.auditName = ''
      this.editForm.remarks = ''
      this.editForm.auditStatus = 1
      this.editForm.applicantId = ''
      this.editForm.applicant = ''
      this.editForm.priority = []
      this.editForm.selectModule = []
      this.moduleList = []
      this.drawerType = 'add'
      this.$refs.editForm.clearValidate()
      this.drawerVisible = false
    }
  }
}
</script>

<style lang="scss">
.audit-process-drawer {
  .user-form {
    padding: 15px;
    border: 1px solid $border-color;
    min-height: 100px;
    text-align: center;
    .new-button {
      line-height: 70px;
    }
    .user-title {
      margin-bottom: 10px;
    }
    .button-col-left {
      min-height: 1px;
      line-height: 40px;
      .el-button.is-circle {
        padding: 3px;
        .icon-svg {
          font-size: 16px;
        }
      }
    }
    .button-col-left {
      text-align: left;
    }
    .button-col-top {
      position: absolute;
      top: -9px;
      right: 2px;
      padding: 3px;
    }
    .el-form-item {
      margin-bottom: 16px;
    }
    .el-select {
      width: 100%;
    }
  }
  .proc-name {
    margin-right: 10px;
  }
  .priority-form {
    margin-bottom: 10px;
  }
  .el-transfer {
    text-align: center;
    line-height: normal;
    .el-transfer-panel__filter {
      width: auto !important;
    }
    .el-transfer-panel {
      width: calc(50% - 62px);
      text-align: left;
    }
  }
}
</style>
